package com.github.fuse.handler;

import com.github.fuse.annotation.ExceptionRatio;
import com.github.fuse.annotation.Fuse;
import com.github.fuse.entity.AopExecute;
import com.github.fuse.exception.FuseException;
import com.github.limit.util.LimitUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @author: wangdejun
 * @create: 2019-10-17 19:22
 **/
public class ExceptionRatioFuseHandler extends AbstractFuseHandler<ExceptionRatio> {
    @Override
    public Class<? extends Annotation> getType() {
        return ExceptionRatio.class;
    }

    @Override
    public Object doHandler(AopExecute aopExecute, ExceptionRatio exceptionRatio) throws Throwable {
        return aopExecute.getJoinPoint().proceed(aopExecute.getParams());
    }

    @Override
    public Object fuseMethod(Throwable e, AopExecute aopExecute, ExceptionRatio exceptionRatio) throws Throwable {
        String fuseMethod = exceptionRatio.fuseMethod();
        if (StringUtils.isBlank(fuseMethod)) {
            throw new FuseException("execute exception", e);
        }
        Class<?> clazz = aopExecute.getEntity().getClass();
        Method method = clazz.getMethod(fuseMethod, aopExecute.getParamTypes());
        return method.invoke(aopExecute.getEntity(), aopExecute.getParams());
    }
}
